/*
*  Copyright 2019-2020 Zheng Jie
*
*  Licensed under the Apache License, Version 2.0 (the "License");
*  you may not use this file except in compliance with the License.
*  You may obtain a copy of the License at
*
*  http://www.apache.org/licenses/LICENSE-2.0
*
*  Unless required by applicable law or agreed to in writing, software
*  distributed under the License is distributed on an "AS IS" BASIS,
*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*  See the License for the specific language governing permissions and
*  limitations under the License.
*/
package me.zhengjie.modules.biz.service.impl;

import cn.hutool.core.convert.Convert;
import io.swagger.models.auth.In;
import me.zhengjie.modules.biz.domain.EntranceGuardCard;
import me.zhengjie.modules.biz.domain.Lab;
import me.zhengjie.modules.biz.service.dto.SensorDto;
import me.zhengjie.modules.system.domain.User;
import me.zhengjie.modules.system.repository.UserRepository;
import me.zhengjie.utils.*;
import lombok.RequiredArgsConstructor;
import me.zhengjie.modules.biz.repository.EntranceGuardCardRepository;
import me.zhengjie.modules.biz.service.EntranceGuardCardService;
import me.zhengjie.modules.biz.service.dto.EntranceGuardCardDto;
import me.zhengjie.modules.biz.service.dto.EntranceGuardCardQueryCriteria;
import me.zhengjie.modules.biz.service.mapstruct.EntranceGuardCardMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

import java.util.List;
import java.util.Map;
import java.io.IOException;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.LinkedHashMap;

/**
* @website https://eladmin.vip
* @description 服务实现
* @author Admin
* @date 2023-02-17
**/
@Service
@RequiredArgsConstructor
public class EntranceGuardCardServiceImpl implements EntranceGuardCardService {

    private final EntranceGuardCardRepository entranceGuardCardRepository;
    private final EntranceGuardCardMapper entranceGuardCardMapper;

    private final UserRepository userRepository;

    @Override
    public Map<String,Object> queryAll(EntranceGuardCardQueryCriteria criteria, Pageable pageable){
        Page<EntranceGuardCard> page = entranceGuardCardRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        Page<EntranceGuardCardDto> dto = page.map(entranceGuardCardMapper::toDto);
        List<EntranceGuardCardDto> resultDto = dto.getContent();
        for (EntranceGuardCardDto entranceGuardCardDto:resultDto) {
            User creator = userRepository.findById(Convert.toLong(entranceGuardCardDto.getCreatorId())).orElseGet(User::new);
            entranceGuardCardDto.setCreateName(creator.getUsername());
            User user = userRepository.findById(Convert.toLong(entranceGuardCardDto.getUserId())).orElseGet(User::new);
            entranceGuardCardDto.setUserName(user.getUsername());
        }

        return PageUtil.toPage(dto);
    }

    @Override
    public List<EntranceGuardCardDto> queryAll(EntranceGuardCardQueryCriteria criteria){
        List<EntranceGuardCard> entranceGuardCardList = entranceGuardCardRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder));
        List<EntranceGuardCardDto> entranceGuardCardDtoList = entranceGuardCardMapper.toDto(entranceGuardCardList);
        for (EntranceGuardCardDto entranceGuardCardDto : entranceGuardCardDtoList) {
            User creator = userRepository.findById(Convert.toLong(entranceGuardCardDto.getCreatorId())).orElseGet(User::new);
            entranceGuardCardDto.setCreateName(creator.getUsername());
            User user = userRepository.findById(Convert.toLong(entranceGuardCardDto.getUserId())).orElseGet(User::new);
            entranceGuardCardDto.setUserName(user.getUsername());
        }
        return entranceGuardCardDtoList;
    }

    @Override
    @Transactional
    public EntranceGuardCardDto findById(Integer id) {
        EntranceGuardCard entranceGuardCard = entranceGuardCardRepository.findById(id).orElseGet(EntranceGuardCard::new);
        ValidationUtil.isNull(entranceGuardCard.getId(),"EntranceGuardCard","id",id);
        return entranceGuardCardMapper.toDto(entranceGuardCard);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public EntranceGuardCardDto create(EntranceGuardCard resources) {
        resources.setCreatorId(Convert.toInt(SecurityUtils.getCurrentUserId()));

        return entranceGuardCardMapper.toDto(entranceGuardCardRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(EntranceGuardCard resources) {
        EntranceGuardCard entranceGuardCard = entranceGuardCardRepository.findById(resources.getId()).orElseGet(EntranceGuardCard::new);
        ValidationUtil.isNull( entranceGuardCard.getId(),"EntranceGuardCard","id",resources.getId());
        entranceGuardCard.copy(resources);
        entranceGuardCardRepository.save(entranceGuardCard);
    }

    @Override
    public void deleteAll(Integer[] ids) {
        for (Integer id : ids) {
            entranceGuardCardRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<EntranceGuardCardDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (EntranceGuardCardDto entranceGuardCard : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("卡号", entranceGuardCard.getNo());
            map.put("使用者", entranceGuardCard.getUserName());
            map.put("有效期", entranceGuardCard.getExpiredAt());
            map.put("创建者", entranceGuardCard.getCreateName());
            map.put("备注", entranceGuardCard.getNote());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }


    @Transactional(rollbackFor = Exception.class)
    public void changeStatus(Integer id, Integer status) {
        entranceGuardCardRepository.updateById(id, status);
    }
}
